package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.MiaoshaUserDao;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.exception.GlobalException;
import com.imooc.miaosha.redis.MiaoshaUserKey;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.util.MD5Util;
import com.imooc.miaosha.util.UUIDUtil;
import com.imooc.miaosha.vo.LoginVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class MiaoshaUserService {
    public static final String COOKI_NAME_TOKEN = "token";
    private static Logger logger = LoggerFactory.getLogger(MiaoshaUserService.class);
    @Autowired
    private MiaoshaUserDao miaoshaUserDao;

    @Autowired
    private RedisService redisService;

    public MiaoshaUser getById(long id) {
        //取缓存
        MiaoshaUser miaoshaUser = redisService.get(MiaoshaUserKey.getById, "" + id, MiaoshaUser.class);
        if (miaoshaUser != null) {
            return miaoshaUser;
        }
        //取数据库
        miaoshaUser = miaoshaUserDao.getById(id);
        if (miaoshaUser != null){
            redisService.set(MiaoshaUserKey.getById, ""+id, miaoshaUser);
        }

        return miaoshaUser;
    }

    public boolean updatePassword(String token, long id, String formPass) {
        //取user
        MiaoshaUser user = getById(id);
        if(user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //更新数据库
        MiaoshaUser toBeUpdate = new MiaoshaUser();
        toBeUpdate.setId(id);
        toBeUpdate.setPassword(MD5Util.formPassToDBPass(formPass, user.getSalt()));
        miaoshaUserDao.update(toBeUpdate);
        //处理缓存
        redisService.delete(MiaoshaUserKey.getById, "" +id);
        user.setPassword(toBeUpdate.getPassword());
        redisService.set(MiaoshaUserKey.token, token, user);

        return  true;
    }

    public String login(HttpServletResponse response, LoginVo vo) {
        if (vo == null) {
            logger.info("MiaoshaUserService@vo is null");
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = vo.getMobile();
        String formPass = vo.getPassword();
        //判断手机号是否存在
        MiaoshaUser user = getById(Long.parseLong(mobile));
        if (user == null) {
            logger.info("MiaoshaUserService@user is null");
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        String dbPassword = user.getPassword();
        String salt = user.getSalt();
        String md5Pass = MD5Util.formPassToDBPass(formPass, salt);
        if (!md5Pass.equals(dbPassword)) {
            logger.info("MiaoshaUserService@formPass = " + formPass + ":dbPassword = " + dbPassword);
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        //登陆成功后给用户生成一个token，利用cookie保存在客户端，
        //然后客户端每次访问都携带这个cookie，服务器通过cookie校验客户
        //生成cookie
        String token = UUIDUtil.uuid();
        addCookie(response, token, user);

        return token;
    }


    public MiaoshaUser getByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //延长有效期
        logger.info("MiaoshaUserService#getByToken#token" + token);
        MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        if (user != null) {
            logger.info("MiaoshaUserService#getByToken#user=null");
            addCookie(response, token, user);
        }

        return user;
    }

    private void addCookie(HttpServletResponse response, String token, MiaoshaUser user) {
        redisService.set(MiaoshaUserKey.token, token, user);
        Cookie cookie = new Cookie(COOKI_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
        cookie.setPath("/");
        logger.info(cookie.getName() + ":" + cookie.getValue());
        response.addCookie(cookie);
    }
}
